package com.ywwxhz.plugins.battery;

import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.BatteryManager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;

import com.ywwxhz.Interface.IModleService;
import com.ywwxhz.Util.PreferencesKit;
import com.ywwxhz.Util.ToolKit;
import com.ywwxhz.plugins.battery.receiver.BatteryReceiver;
import com.ywwxhz.plugins.battery.widget.BatteryWidget;
import com.ywwxhz.taskmgr.R;

public class BatteryModel implements IModleService {
    public static final int LINE_ENABLE = 1;
    public static final int LINE_DISABLE = 2;
    public static final int WIDGET_ENABLE = 3;
    public static final int WIDGET_DISABLE = 4;
    public static final int INFO_UPDATE = 5;
    public static final int MODEL = 2;
    public static final String PARAM = "BATTERY_PARAM";
    public static BatteryModel instance;
    private Context context;
    private boolean batteryrec = false;
    private WindowManager mWindowManager;
    private LayoutParams mLayoutParams;
    private BatteryLine mBatteryLine;
    private BatteryReceiver mReceiver;
    private long batterytime;
    private boolean batteryline = false;
    private boolean batteryWidget = false;
    private String TAG = "Battery Mode";

    private BatteryModel(Context context) {
        this.context = context;
        mReceiver = new BatteryReceiver();
        onRecover(context);
    }

    public static BatteryModel getInstance(Context context) {
        if (instance == null) {
            instance = new BatteryModel(context);
        }
        return instance;
    }

    /**
     * 注册电量变化广播
     */
    private void batteryReceiver(boolean enable) {
        if (enable) {
            if (!batteryrec) {
                try {
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(Intent.ACTION_BATTERY_CHANGED);
                    filter.addAction(Intent.ACTION_POWER_CONNECTED);
                    filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
                    context.registerReceiver(mReceiver, filter);
                } catch (Exception ignored) {
                }
                batteryrec = true;
            }
        } else {
            if (!batteryline && !batteryWidget) {
                try {
                    context.unregisterReceiver(mReceiver);
                    batteryrec = false;
                } catch (Exception ignored) {
                }
            }
        }
    }

    /**
     * 获取电池情况
     */
    private void GetBatteryInfo() {
        long currenttime = System.currentTimeMillis();
        Intent batteryInfoIntent = context.getApplicationContext().registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        assert batteryInfoIntent != null;
        int level = batteryInfoIntent.getIntExtra("level", 0);
        int plugged = batteryInfoIntent.getIntExtra("plugged", 0);
        if (batteryWidget) {
            if (batterytime == 0) {
                batterytime = System.currentTimeMillis();
                PreferencesKit.writeLong(context, "batterytime", batterytime);
            }
            float temperature = batteryInfoIntent.getIntExtra("temperature", 0); // 温度的单位是10℃
            RemoteViews localRemoteViews = new RemoteViews(context.getPackageName(),
                    R.layout.batterymonitor);
            localRemoteViews.setTextViewText(R.id.remain, String.format("%3d%%", level));
            localRemoteViews.setTextViewText(R.id.temp, String.format("%.1f℃", temperature / 10));
            if (plugged != 0) {
                String mBatteryType = "充电";
                switch (plugged) {
                    case BatteryManager.BATTERY_PLUGGED_AC:
                        mBatteryType = "AC";
                        break;
                    case BatteryManager.BATTERY_PLUGGED_USB:
                        mBatteryType = "USB";
                        break;
                    case BatteryManager.BATTERY_PLUGGED_WIRELESS:
                        mBatteryType = "Wireless";
                        break;
                }
                localRemoteViews.setViewVisibility(R.id.charging, View.VISIBLE);
                localRemoteViews.setTextViewText(R.id.status, mBatteryType);
            } else {
                localRemoteViews.setViewVisibility(R.id.charging, View.GONE);
                localRemoteViews.setTextViewText(R.id.status, "放电");
            }
            localRemoteViews.setTextViewText(R.id.usetime,
                    ToolKit.FormatTime(currenttime - batterytime));
            ComponentName localComponentName = new ComponentName(context, BatteryWidget.class);
            AppWidgetManager.getInstance(context).updateAppWidget(localComponentName,
                    localRemoteViews);
        }
        if (batteryline) {
            try {
                mBatteryLine.setBatteryRemain(level, plugged != 0);
                mWindowManager.updateViewLayout(mBatteryLine, mLayoutParams);
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * 显示顶部电量条
     */
    private void showBatteryLine(boolean enable) {
        if (enable) {
            if (!batteryline) {
                if (mWindowManager == null) {
                    createWindowManager();
                }
                /**
                 * 创建悬浮窗体
                 */
                mBatteryLine = new BatteryLine(context);
                try {
                    mWindowManager.addView(mBatteryLine, mLayoutParams);
                } catch (Exception ignored) {
                }
            }
        } else {
            try {
                mWindowManager.removeView(mBatteryLine);
            } catch (Exception ignored) {
            }
        }
        batteryline = enable;
    }

    /**
     * 创建置顶窗体
     */
    private void createWindowManager() {
        // 取得系统窗体
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        // 窗体的布局样式
        mLayoutParams = new WindowManager.LayoutParams();

        // 设置窗体显示类型——TYPE_SYSTEM_OVERLAY(系统提示)
        mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;

        // 设置窗体焦点及触摸：
        // FLAG_NOT_FOCUSABLE(不能获得按键输入焦点)
        mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        // 设置显示的模式
        mLayoutParams.format = PixelFormat.RGBA_8888;

        // 设置对齐的方法
        mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;

        // 设置窗体宽度和高度
        mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        // 设置窗体显示的位置，否则在屏幕中心显示
        mLayoutParams.x = 0;
        mLayoutParams.y = 0;
    }

    public void execute(Intent intent) {
        ToolKit.Log(TAG, "" + intent.getExtras().toString());
        switch (intent.getIntExtra(PARAM, 0)) {
            case LINE_ENABLE:
                batteryReceiver(true);
                showBatteryLine(true);
                GetBatteryInfo();
                break;
            case LINE_DISABLE:
                batteryReceiver(false);
                showBatteryLine(false);
                break;
            case WIDGET_ENABLE:
                batteryReceiver(true);
                batteryWidget = true;
                GetBatteryInfo();
                break;
            case WIDGET_DISABLE:
                batteryWidget = false;
                batteryReceiver(false);
                break;
            case INFO_UPDATE:
                if (intent.getIntExtra("charge", 0) == 1) {
                    batterytime = System.currentTimeMillis();
                    PreferencesKit.writeLong(context, "batterytime", batterytime);
                }
                GetBatteryInfo();
                break;
            default:
                break;
        }
    }

    public void onConfigChange(Configuration newConfig) {
        if (getStatus()) {
            mBatteryLine.updateWidth();
            GetBatteryInfo();
        }
    }

    public void onDestroy() {
        try {
            context.unregisterReceiver(mReceiver);
        } catch (Exception ignored) {
        }
        context = null;
        instance = null;
    }

    @Override
    public boolean getStatus() {
        return batteryline || batteryWidget;
    }

    @Override
    public void onRecover(Context context) {
        this.context = context;
        batteryrec = false;
        ComponentName localComponentName = new ComponentName(context, BatteryWidget.class);
        showBatteryLine(PreferencesKit.getboolean(context, context.getString(R.string.pref_batteryline_key), false));
        if (AppWidgetManager.getInstance(context).getAppWidgetIds(localComponentName).length > 0) {
            batteryWidget = true;
        }
        if (batteryline || batteryWidget) {
            batterytime = PreferencesKit.getLong(context, "batterytime", System.currentTimeMillis());
            GetBatteryInfo();
        }
        batteryReceiver(batteryline || batteryWidget);
    }
}
